package com.example.dbmeta.meta.common;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.net.NetUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import javax.annotation.PostConstruct;
import java.io.Serializable;
@Slf4j
public class MyIdGeneratorConfig implements IdentifierGenerator {
    public static long WORKER_ID = 1;
    public static long DATACENTER_ID = 1;

    private Snowflake snowflake = IdUtil.createSnowflake(WORKER_ID, DATACENTER_ID);

    //@Value("${my.snowflake.worker-id}")
    private long configuredWorkerId=5L;

    @PostConstruct
    public void init() {
        // 使用配置或基于IP生成合法workerId
        WORKER_ID = configuredWorkerId != 0 ? configuredWorkerId : Math.abs(NetUtil.getLocalhostStr().hashCode()) % 32;
        this.snowflake = IdUtil.createSnowflake(WORKER_ID, DATACENTER_ID);
        log.info("当前机器的WORKER_ID: {}", WORKER_ID);
    }

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
        return snowflake.nextId();
    }
}
